<template>
  <div class="search">
    <!-- 1.顶部导航栏 -->
    <van-nav-bar left-arrow title="搜索中心" @click-left="$router.back()">
    </van-nav-bar>
    <!-- 2.搜索框 -->
    <van-search
      show-action
      placeholder="请输入搜索关键词"
      shape="round"
      v-model.trim="keyword"
      @input="onInput"
    >
      <template #action>
        <div @click="$router.push({path:'/searchResult',query:{keyword}})">搜索</div>
      </template>
    </van-search>

    <!-- 3.推荐词 -->
    <van-cell-group>
      <van-cell v-for="(item,index) in showList" :key="item" icon="search" 
      @click="$router.push({path:'/searchResult',query:{keyword:suggestionList[index]}})">
        <template #title>
          <div v-html="item"></div>
        </template>
      </van-cell>
    </van-cell-group>

    <!-- 4.搜索历史 -->
    <van-cell-group>
      <van-cell title="历史记录"> </van-cell>
      <van-cell v-for="item in historyList" :key="item" :title="item">
        <van-icon name="close" @click="deleteHistory"/>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { getSuggestion,getSearchHistory,deleteSearchHistory } from './home.js'
export default {
  name: 'Search',
  data () {
    return {
      keyword: '', // 搜索关键字
      suggestionList: [], //推荐词列表
      timeID: null, //防抖定时器
      historyList:[]//搜索历史
    }
  },
  methods: {
    onInput () {
      /* 输入框防抖处理 */
      //1.先清除上一次的定时器，以最后一次触发为准
      clearTimeout(this.timeID)
      //2.开启防抖定时器
      this.timeID = setTimeout(async () => {
        // 检查当前关键字是否为空
        if (this.keyword == '') {
          this.suggestionList = []
          return
        }
        // 调用方法, 发送请求
        const res = await getSuggestion(this.keyword)
        this.suggestionList = res.data.data.options
      }, 500)
    },
    async deleteHistory(item){
      let res = await deleteSearchHistory({message:item})
      console.log( res );
      if(res.status == 204){
        this.$toast.success('删除成功')
        this.historyList = []
      }else{
        this.$toast.fail('删除失败')
      }  
    }
  },
  computed: {
    showList () {
      //(1)创建正则 ： 全局匹配当前搜索框内容，  g:全局匹配  i:不区分大小写
      const reg = new RegExp(this.keyword, 'gi')
      //(2)map映射数组
      return this.suggestionList.map(item => {
        //将搜索结果替换为<span>标签
        return item.replace(
          reg,
          match => `<span style="color: red;">${match}</span>`
        )
      })
    }
  },
  async created() {
      let res = await getSearchHistory()
      console.log(res);
      this.historyList = res.data.data.keywords
  },
}
</script>

<style lang="less"></style>
